// 创建Toast提示
window.createToast = (message, type = 'info') => {
  const toast = document.createElement('div');
  toast.style.cssText = `
	position: fixed;
	top: 50%;
	left: 50%;
    padding: 12px 24px;
    border-radius: 4px;
    color: white;
    z-index: 10000;
    font-family: system-ui;
    font-size: 14px;
    animation: fadeIn 0.3s, fadeOut 0.3s 2.7s;
    background-color: ${
      type === 'success' ? '#4CAF50' :
      type === 'error' ? '#f44336' : 
      '#2196F3'
    };
  `;
  
  toast.textContent = message;
  document.body.appendChild(toast);
  
  setTimeout(() => toast.remove(), 3000);
};

// 样式
const style = document.createElement('style');
style.textContent = `
  @keyframes fadeIn {
    from { opacity: 0; transform: translateY(-20px); }
    to { opacity: 1; transform: translateY(0); }
  }
  @keyframes fadeOut {
    from { opacity: 1; transform: translateY(0); }
    to { opacity: 0; transform: translateY(-20px); }
  }
`;
document.head.appendChild(style);

// 等待iframe加载
function waitForIframe() {
  return new Promise((resolve) => {
    const check = () => {
      const iframe = document.querySelector('iframe');
      if (iframe?.contentDocument?.getElementById('DataGrid1')) {
        resolve(iframe);
      } else {
        setTimeout(check, 500);
      }
    };
    check();
  });
}

// 处理成绩数据
async function processGrades(data) {
  try {
    const iframe = await waitForIframe();
    if (!iframe) {
      createToast('请确保成绩页面已加载', 'error');
      return;
    }

    const iframeDoc = iframe.contentDocument;
    console.log("=== 开始处理 ===");
    createToast('开始导入成绩...', 'info');
    
    const workbook = XLSX.read(data, { type: 'array' });
    const worksheet = workbook.Sheets[workbook.SheetNames[0]];
    const rows = XLSX.utils.sheet_to_json(worksheet, {header: 1});
    
    let successCount = 0;
    let errorCount = 0;
    const errors = [];

    // 从第2行开始读取（A2开始）
    for (let i = 1; i < rows.length; i++) {
      const row = rows[i];
      if (!row?.length) continue;

      // 列对应关系：A列是学号，B列是姓名，C列平时成绩，D列期末成绩
      const studentId = String(row[0]);  // A列
      const studentName = row[1];        // B列
      const psScore = row[2];           // C列
      const qmScore = row[3];           // D列

      if (!studentId || !psScore || !qmScore) {
        errors.push(`第${i+2}行数据不完整`);  // i+2因为我们是从第2行开始的
        errorCount++;
        continue;
      }

      console.log(`处理: 学号=${studentId}, 姓名=${studentName}`);
      
      const tableRows = iframeDoc.querySelectorAll('#DataGrid1 tr');
      let found = false;

      for (const tr of tableRows) {
        const idCell = tr.cells[1];
        if (idCell?.textContent?.trim() === studentId) {
          const psInput = tr.querySelector('input[id*="_ps"]');
          const qmInput = tr.querySelector('input[id*="_qm"]');
          
          if (psInput && qmInput) {
            psInput.value = psScore;
            qmInput.value = qmScore;
			// 正方系统要求输入成绩后触发计算总评等
			// 所以要模拟用户输入行为
            psInput.dispatchEvent(new Event('change'));
            qmInput.dispatchEvent(new Event('change'));
            successCount++;
            found = true;
            break;
          }
        }
      }

      if (!found) {
        errors.push(`未找到学号: ${studentId}`);
        errorCount++;
      }
    }

    createToast(
      `处理完成! 成功:${successCount} 失败:${errorCount}`,
      successCount > 0 ? 'success' : 'error'
    );

    if (successCount > 0) {
      setTimeout(() => {
        createToast('请记得点击"保存"按钮!', 'info');
      }, 1000);
    }

    console.log('=== 处理结果 ===');
    console.log(`成功: ${successCount} 失败: ${errorCount}`);
    if (errors.length) console.log('错误:', errors);

  } catch (error) {
    console.error('处理失败:', error);
    createToast('处理失败，请重试', 'error');
  }
}

// 监听消息
window.addEventListener('message', async (event) => {
  if (event.data.type === 'IMPORT_GRADES') {
    await processGrades(new Uint8Array(event.data.data));
  }
});